/**
 * Created by yuji on 2015/10/28.
 */
'use strict'
var util = require('./util');

/**
 * 抽取依赖
 * 递归的将依赖提取出来
 * @param filePath
 * @param mapRev
 */



var calDeps = function(fileObj){
    switch (fileObj.type){
        case "css":
            fileObj.content = fileObj.content.toString();
            return calDepsCss(fileObj);
            break;
        default :
            return new Set;
    }

}

/**
 * 考虑用 url() 以及@import() 引入的情况
 * @param fileObj
 * @param mapRev
 */
var calDepsCss = function(fileObj){
    var deps = new Set;
    var urlCss = /url\(\s*[^(]*\)/g;
    var content = fileObj.content.replace(urlCss,function(value){
        value = value.replace(/'/g,'').replace(/"/g,"").replace(/\s/g,'');
        var name = value.slice(4,-1);
        var resolvedPath = util.parsePath(fileObj.dir, name);
        deps.add(resolvedPath);
        return 'url(<%- data["'+ resolvedPath + '"]%>)';
    })
    fileObj.template = content;
    return deps
}

//@TODO 处理方式不一样,等规范完善了再说……
//js依赖的处理，js不需要要改依赖的资源名，可以当作图片处理直接生成哈希
//js的依赖是个依赖树……
var calDepsJs = function(fileObj, mapRev){

}

/**
 *Tested
 * 生成有序依赖
 * @param fileList
 * @param mapRes
 */
var orderlyDeps = function(fileList, mapRes){
    let cache = new Set;
    let list = new Set(fileList);
    var arr = [];
    var resArr = [];

    let cal = function(item){
        if(cache.has(item)) return;
        cache.add(item);
        arr.push(item);
        var ress = util.set2array(mapRes.deps(item));
        ress.forEach(function(value){
            if(list.has(value)){
                cal(value);
            }
        })

    }

    for(let i of list){
        if(cache.has(i)) continue;
        resArr = resArr.concat(arr.reverse().slice());
        arr = [];
        cal(i);
    }
    resArr = resArr.concat(arr.reverse().slice());
     return resArr;
}

/**
 * Tested
 * 生成需要重新构建的文件的列表
 * @param fileList
 * @param mapRev
 */
var recalFileList = function(fileList, mapRev){
    var fileSet = new Set(fileList);
    for(var item of fileSet){
            if(util.hasProp(mapRev.map,item)){
                mapRev.map[item].forEach(function(key){
                    fileSet.add(key);
                })
            }

        }
    return fileSet;

}



exports.calDeps = calDeps;

exports.orderlyDeps = orderlyDeps;

exports.recalFileList = recalFileList;